import pyautogui
import json
import time
import os

from typing import Any, Callable, List


CONFIG_NAME = 'config.json'

class PositionData(object):

    def __init__(self, x:int, y:int, interval:float) -> None:
        self.x = x
        self.y = y
        self.interval = interval
        """点击坐标后等待时长"""

class ConfigInfo(object):

    def __init__(self, loop_max_count=0) -> None:
        """这些存在的值是为了生成config.json文件填充其格式而添加

        Args:
            loop_max_count (int, optional): 循环列表点击的最大次数. Defaults to 0.
        """
        self.loop_max_count = loop_max_count
        self.begin_posi_list:List[PositionData] = [PositionData(100,200,1.0),]
        self.loop_posi_list:List[PositionData] = [PositionData(100,200,1.0), PositionData(1000, 200, 1.5)]
        self.ended_posi_list:List[PositionData] = [PositionData(100,200,1.0),]

class JSONEncoder(json.JSONEncoder):

    def default(self, o: ConfigInfo) -> dict:
        
        d = {}
        for k,v in o.__dict__.items():
            if k.startswith('_'):
                continue
            d.setdefault(k, v)
        return d

class JSONDecoder(json.JSONDecoder):

    def decode(self, s: str, _w: Callable[..., Any] = ...) -> ConfigInfo:
        obj_data =  super().decode(s)
        obj = ConfigInfo()
        for k,v in obj_data.items():
            if isinstance(v, list):
                dt = []
                for pos in v:
                    dt.append(PositionData(**pos))
                setattr(obj, k, dt)
            else:
                setattr(obj, k, v)
        return obj

def read_local_config() -> ConfigInfo:

    with open(CONFIG_NAME) as fp:
        return json.load(fp, cls=JSONDecoder)

if __name__ =='__main__':

    # with open(CONFIG_NAME, 'w') as f:
    #     f.write(json.dumps(ConfigInfo(5), indent=4, cls=JSONEncoder))

    config = read_local_config()

    count = 0
    stop = False
    if len(config.begin_posi_list):
        for pos in config.begin_posi_list:
            count += 1
            xy = pos.x, pos.y
            print("begin : %d\tclick : %d, %d" % (count, *xy))
            pyautogui.click(xy)
            time.sleep(pos.interval)
    count = 0
    while True:
        if not len(config.loop_posi_list):
            break
        for pos in config.loop_posi_list:
            count += 1
            xy = pos.x, pos.y
            print("loop count : %d\tclick : %d, %d" % (count, *xy))
            pyautogui.click(*xy)
            if count >= config.loop_max_count:
                stop = True
                break
            time.sleep(pos.interval)
        if stop:
            break
    count = 0
    if len(config.ended_posi_list):
        for pos in config.ended_posi_list:
            count += 1
            xy = pos.x, pos.y
            print("begin : %d\tclick : %d, %d" % (count, *xy))
            pyautogui.click(xy)
            time.sleep(pos.interval)
    print("exit")
    os.system("pause")